package com.example.javaweb.controller;

import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.concurrent.TimeUnit;

/**
 * @author: dtYuMa
 * @date: 2021年08月18日 17:36
 * @description:
 */
@Slf4j
@RestController
@RequestMapping("/sse")
public class SSEController {

    @RequestMapping(value = "/push")
    public void push(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        String param = req.getParameter("param");
        log.info(param);
        resp.setContentType("text/event-stream;charset=utf-8");
        PrintWriter out = resp.getWriter();
        //使用无限循环的原因：实现客户端只发送一次请求，服务器不断地单向推送消息，保持长连接。否则，数据发送完了，就会断开连接，默认3s之后重连，会发起新的请求，
        //这样不断的发送新的请求，会增加服务器的压力
        for (; ; ) {
            log.info("客户端连接中...");

            //客户端断开连接，跳出循环，服务器不再推送消息
            if (out.checkError()) {
                log.info("客户端断开连接...");
                return;
            }

            out.write("data: hello world!\n\n");
            out.flush();

            try {
                TimeUnit.SECONDS.sleep(5);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}
